package hapi.cpp;

import haxe.PosInfos;
import haxe.Timer;
import nme.events.Event;
import nme.events.KeyboardEvent;
import nme.Lib;
import nme.text.TextField;
import nme.text.TextFormat;

class AndroidUtil {

	static var traceTextField:TextField;
	static var onBackPressed:Void->Void = function() { };
	static var keyListenerRegistered:Bool = false;
	
	public static function callOnBackPressed(func:Void->Void) {
		if (!keyListenerRegistered) {
			onBackPressed = func;
			nme.Lib.current.stage.addEventListener(nme.events.KeyboardEvent.KEY_DOWN, checkBackKey, false, 99999999);
			keyListenerRegistered = true;
		}
	}
	
	public static function enableTouchMode() {
		var mMultiTouch = nme.ui.Multitouch.supportsTouchEvents;
		if (mMultiTouch) nme.ui.Multitouch.inputMode = nme.ui.MultitouchInputMode.TOUCH_POINT;
	}
	
	public static function enableTimers() {
		nme.Lib.current.addEventListener( Event.ENTER_FRAME, function(e) { nme.Timer.nmeCheckTimers(); } );
	}
	
	public static function redirectTraces() {
		if(traceTextField == null) {
			traceTextField = new TextField();
			traceTextField.width = nme.Lib.current.stage.stageWidth;
			traceTextField.height = nme.Lib.current.stage.stageHeight-10;
			traceTextField.defaultTextFormat = new TextFormat("Arial", 20, 0x000000, false);
			traceTextField.multiline = true;
			traceTextField.mouseEnabled = false;
			traceTextField.text = " ";
			haxe.Log.trace = function(v, ?infos:PosInfos) { 
				println(infos.fileName + ":" + infos.lineNumber + ": " + v);
			}
		}else if (traceTextField.parent != null) {
			traceTextField.parent.removeChild(traceTextField);
		}
		nme.Lib.current.addChild(traceTextField);
	}
	
	public static function println(msg:String) {
		traceTextField.text = traceTextField.text + msg + "\n";
		traceTextField.scrollV = traceTextField.maxScrollV;
	}
	
	static function checkBackKey(event:KeyboardEvent) {
		if (event.charCode == 27) {
			onBackPressed();
		}
	}
}
